import { defineStore } from 'pinia';
import file from '@/utils/file/index.js'
import menus from '@/api/menus/index.js'
import schools from '@/api/schools/index.js'
import systems from '@/api/systems/index.js'
import recommends from '@/api/recommends/index.js'

export const useGeneralStore = defineStore('general', {
	state: () => {
		return {
			complete: false,
			menuList: [],
			systemData: { gold: {}, base: {} },
			recommendList: []
		};
	},
	actions: {
		async init() {
			const beforeMenu = this.getMenuList();
			const beforeSystems = this.getSystemData();
			const beforeRecommend = this.getRecommendList();

			await Promise.allSettled([beforeMenu, beforeSystems, beforeRecommend])
			this.complete = true;
		},
		async getRecommendList() {
			const response = await recommends.getList();
			if (response['code'] === 200) {
				this.recommendList = response['data'].map(item => {
					item['image'] = file.getFileUrl(item['image'])
					return item;
				})
			}
		},
		async getMenuList() {
			const response = await menus.getList();
			if (response['code'] === 200) {
				this.menuList = response['data'].map(item => {
					item['icon'] = file.getFileUrl(item['icon'])
					item['bg_img'] = file.getFileUrl(item['bg_img'])
					return item;
				})
			}
		},
		async getSystemData() {
			const response = await systems.get();
			if (response['code'] === 200) {
				const objs = {};
				const test = uni.$uv.test;
				const data = response['data'];
				for (const [key, item] of Object.entries(data)) {
					objs[item['type']] = test.jsonString(item['value']) ? JSON.parse(item['value']) : item['value'];
				}

				this.systemData = objs;

				const shareData = objs['share'];
				uni.$u.shareParams = {
					title: shareData['title'],
					desc: shareData['description'],
					imageUrl: file.getFileUrl(shareData['img']),
				}
			}
		},
	}
});